<template>
  <list-searcher :searchList="searchList" v-model:searchForm="stockState.queryParam" @loadData="loadData" @reset="onReset">
    <template #shortcutTime>
      <a-spin :loading="initLoading" style="margin-left: -70px">
        <a-space>
          <a-button type="outline" @click="handleShortcutTime('today')">今天</a-button>
          <a-button type="outline" @click="handleShortcutTime('nextWeek')">下两周</a-button>
          <a-button type="outline" @click="handleShortcutTime('nextMonth')">下一月</a-button>
        </a-space>
      </a-spin>
    </template>
  </list-searcher>
  <!-- 标签 -->
  <TagList ref="tagListRef" :data="stockState.statistics" :selectable="true" @change="tagChange" />
  <!-- 骨架屏 -->
  <a-skeleton v-if="initLoading" :animation="true">
    <a-skeleton-line :rows="5" :line-height="90" />
  </a-skeleton>
  <!-- 排车table -->
  <StockTable v-else />
</template>

<script lang="ts" setup>
  import { ref, computed, provide, reactive } from 'vue'
  import dayjs from 'dayjs'
  import { getCarSotckData } from '@/api/asset/carStock'
  import StockTable from './components/table/index.vue'
  import { getDayList, ininStockData } from './components/table/tableUtil'
  import TagList from '../components/tag-list.vue'
  import { usePageDict } from '@/hooks/useDict'

  const dict = usePageDict('carStockDict')

  const today = dayjs()
  // 局部状态管理
  const stockState = reactive({
    dayList: [],
    dayPx: 0,
    hourPx: 0,
    stockData: [],
    // 统计
    statistics: {},
    // 接口参数（不包含page信息）
    queryParam: {
      siteId: undefined,
      seriesIdList: undefined,
      modelIdList: undefined,
      carIdList: undefined,
      typeList: [],
      // 默认14天
      dateRange: [today.format('YYYY-MM-DD 00:00:00'), today.add(13, 'day').format('YYYY-MM-DD 23:59:59')],
      startTime: '',
      endTime: '',
    },
    // 滚动位置
    scrollTop: 0,
    scrollLeft: 0,
  })
  provide('stockState', stockState)

  // 查询条件
  let initQueryParam: any
  const searchList = computed(() => {
    const queryParam = stockState.queryParam
    return [
      {
        label: '门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_listBystaff',
          allowClear: false,
          params: {
            siteStatusList: [10, 20],
            oldId: queryParam.siteId,
          },
        },
        initList: (list: any) => {
          const site = list[0]
          if (!site) {
            initLoading.value = false
            return
          }
          stockState.queryParam.siteId = site.id
          initQueryParam = {
            siteId: site.id,
            dateRange: [today.format('YYYY-MM-DD 00:00:00'), today.add(13, 'day').format('YYYY-MM-DD 23:59:59')],
            type: '',
          }
          loadData()
        },
        change: () => {
          stockState.queryParam.seriesIdList = undefined
          stockState.queryParam.modelIdList = undefined
          stockState.queryParam.carIdList = undefined
        },
      },
      {
        label: '车系',
        prop: 'seriesIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_carSeries_bySite',
          mountedLoad: false,
          params: {
            siteId: queryParam.siteId,
          },
        },
        change: () => {
          stockState.queryParam.modelIdList = undefined
          stockState.queryParam.carIdList = undefined
        },
      },
      {
        label: '车型',
        prop: 'modelIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_car_model_bySite',
          mountedLoad: false,
          params: {
            siteId: queryParam.siteId,
            seriesIdList: queryParam.seriesIdList,
          },
        },
        change: () => {
          stockState.queryParam.carIdList = undefined
        },
      },
      {
        label: '车牌号',
        prop: 'carIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_carLicensenno_bySite',
          mountedLoad: false,
          params: {
            siteId: queryParam.siteId,
            seriesIdList: queryParam.seriesIdList,
            modelIdList: queryParam.modelIdList,
          },
        },
      },
      {
        label: '时间',
        prop: 'dateRange',
        type: 'i-range-picker',
        attrs: {
          allowClear: false,
          // showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        disabledDate: (current: string) => {
          const today = dayjs().startOf('day')
          const cur = dayjs(current)
          return cur.isBefore(today) || cur.isAfter(today.add(100, 'day'))
        },
      },
      {
        label: ' ',
        slot: 'shortcutTime',
      },
      {
        label: '订单渠道',
        prop: 'channelTypeList',
        type: 'a-select',
        options: dict.channelTypeEnum,
        attrs: { multiple: true },
      },
    ]
  })

  // 标签切换
  const tagChange = (val: string) => {
    stockState.queryParam.typeList = val
    loadData()
  }
  // 重置
  const tagListRef = ref()
  const onReset = () => {
    stockState.queryParam = { ...initQueryParam }
    tagListRef.value.reset()
  }

  // 加载数据
  const initLoading = ref(false)
  // 最小1天，最大100天
  const calcParamRangtime = () => {
    const query = stockState.queryParam
    const [startTime, endTime] = query.dateRange
    query.startTime = dayjs(startTime).format('YYYY-MM-DD 00:00:00')
    query.endTime = dayjs(endTime).format('YYYY-MM-DD 23:59:59')
  }
  const loadData = () => {
    const query = stockState.queryParam
    calcParamRangtime()
    // 清空库存数据
    initLoading.value = true
    getCarSotckData(query).then((res) => {
      setTimeout(() => {
        initLoading.value = false
      }, 100)
      const { dayList, hourPx, dayPx } = getDayList(query.startTime, query.endTime)
      stockState.dayList = dayList
      stockState.dayPx = dayPx
      stockState.hourPx = hourPx
      stockState.stockData = ininStockData(res.result.list)
      stockState.statistics = res.result.statistics
      stockState.scrollTop = 0
    })
  }
  const syncQueryParam = (queryParam: any) => {
    stockState.queryParam.siteId = queryParam.siteId
    stockState.queryParam.seriesIdList = queryParam.seriesIdList
    stockState.queryParam.modelIdList = queryParam.modelIdList
    stockState.queryParam.startTime = queryParam.startTime
    stockState.queryParam.endTime = queryParam.endTime
    stockState.queryParam.dateRange = queryParam.dateRange
  }
  const getQueryParam = () => {
    return stockState.queryParam
  }

  // 时间快捷选择
  const calcDateRange = (startT: string, addDays: number) => {
    let start = dayjs().startOf('day')
    if (!startT) {
      start = dayjs().startOf('day')
    } else {
      start = dayjs(startT).startOf('day')
    }
    const end = start.add(addDays, 'day').subtract(1, 'second')
    const startTime = start.format('YYYY-MM-DD 00:00:00')
    const endTime = end.format('YYYY-MM-DD 23:59:59')
    stockState.queryParam.dateRange = [startTime, endTime]
  }
  const handleShortcutTime = (type: string) => {
    let startTime = ''
    let addDays = 14
    if (type == 'nextWeek') {
      startTime = stockState.queryParam.dateRange[1]
    } else if (type == 'nextMonth') {
      startTime = stockState.queryParam.dateRange[1]
      addDays = 30
    }
    calcDateRange(startTime, addDays)
    loadData()
  }

  defineExpose({ loadData, syncQueryParam, getQueryParam })
  provide('loadDataFn', loadData)
</script>
